import { FC, MouseEvent } from 'react'
import styles from './EditCanvas.module.scss'
import { useSelector, useDispatch } from 'react-redux'
import { StateType } from '@/store'
import classnames from 'classnames'
import { ComponentInfoType, ComponentsStateType, changeSelected } from '@/store/componentsReducer'
import { getComponentByType } from '@/components/questionComponents'
import useBindCanvasKeyPress from '@/hooks/useBindCanvasKeyPress'
const EditCanvas: FC = () => {
  const { componentList, selectedId } = useSelector<StateType>(state => state.components) as ComponentsStateType
  const dispatch = useDispatch()
  // 根据组件类型获取组件
  const renderer = (cop: ComponentInfoType) => {
    const { type, props } = cop
    if (!type) return null
    const config = getComponentByType(type)
    if (!config) return null
    const { Component } = config
    return <Component {...props} />
  }
  const handelSelected = (e: MouseEvent, id: string) => {
    e.stopPropagation()
    if (!id) return
    dispatch(changeSelected(id))
  }
  // 绑定键盘事件
  useBindCanvasKeyPress()
  return (
    <div className={styles.canvas}>
      {componentList
        .filter(item => !item.isHidden)
        .map(v => {
          const wrapper = styles.wrapper
          const selected = styles.selected
          const locked = styles.locked
          const canvasClassName = classnames({
            [wrapper]: true,
            [selected]: selectedId === v.fe_id,
            [locked]: v.isLocked,
          })
          return (
            <div className={canvasClassName} key={v.fe_id} onClick={e => handelSelected(e, v.fe_id!)}>
              <div className={styles.component}>{renderer(v)}</div>
            </div>
          )
        })}
    </div>
  )
}
export default EditCanvas
